package com.lin.mr.maizilaundry.fragmentcloth;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.lin.mr.maizilaundry.R;
import com.lin.mr.maizilaundry.entity.ClothInfo;
import com.lin.mr.maizilaundry.myadapter.GridViewAdapter;
import com.lin.mr.maizilaundry.myapplication.MyApplication;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 这里采用的是HttpClient请求数据，后被FragmentSpring替代
 */
public class FragmentCloth extends Fragment implements View.OnClickListener {
    private GridView gridView;
    private ImageView iv_float;

    private PopupWindow popupWindow;
    private List<ClothInfo> clothInfoList;
    private ClothInfo clothInfo;
    private ImageView iv_picture;
    private Button btn_sure;
    private ImageButton btn_plus, btn_minus;
    private TextView tv_sum, tv_name, tv_price;

    int touchPosition;//用户触摸GridView中的项的位置

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            gridView.setAdapter(new GridViewAdapter(getContext(), clothInfoList));
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_cloth, container, false);
        iv_float = (ImageView) view.findViewById(R.id.iv_float);
        gridView = (GridView) view.findViewById(R.id.gridView_cloth);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                touchPosition = position;
                showPopupWindow(position);
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    popupWindow.showAtLocation(gridView, Gravity.BOTTOM, 0, 0);
                }
            }
        });
        getClothInfo();
        initPopupWindow();
        //悬浮图标
        if (MyApplication.laundries.size() != 0) {
            iv_float.setImageResource(R.mipmap.laundry_dot);
        } else {
            iv_float.setImageResource(R.mipmap.laundry);
        }
        iv_float.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //此处需要到EventBus
            }
        });


        return view;
    }

//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {

//        if (isVisibleToUser){
//            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                @Override
//                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                    touchPosition = position;
//                    showPopupWindow(position);
//                    if (popupWindow != null && popupWindow.isShowing()){
//                        popupWindow.dismiss();
//                    }else {
//                        popupWindow.showAtLocation(gridView, Gravity.BOTTOM,0,0);
//                    }
//                }
//            });
//        }
//
//    }

    //使用get的方式获取衣服信息
    private void getClothInfo() {
        final String path = "http://cloud.bmob.cn/d9f6840be6bb07cf/wash_spring";
        Thread thread = new Thread() {
            @Override
            public void run() {
                HttpGet httpGet = new HttpGet(path);
                try {
                    HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        String result = EntityUtils.toString(httpResponse.getEntity());
                        pareClothInfo(result);
                    } else {
                        Toast.makeText(getActivity(), "请求失败o(╯□╰)o", Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        };
        thread.start();
    }

    private void pareClothInfo(String result) {
        clothInfoList = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(result);
            JSONArray jsonArray = jsonObject.getJSONArray("washInfo");
            for (int i = 0; i < jsonArray.length(); i++) {
                //获取数组里面的对象
                JSONObject object = jsonArray.getJSONObject(i);
                clothInfo = new ClothInfo();
                clothInfo.setWashHead(object.getString("WashHead"));
                clothInfo.setWashName(object.getString("WashName"));
                clothInfo.setAmount(object.getString("Amount"));
                clothInfoList.add(clothInfo);
            }
            handler.sendEmptyMessage(2);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        //测试是否能够成功解析数据
        for (ClothInfo clothInfo : clothInfoList) {
            Log.e("Tag", clothInfo.toString());
        }
    }

    public void initPopupWindow() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_item, null);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        //设置PopupWindow的属性
        ColorDrawable dw = new ColorDrawable(0xb0000000);//设置背景色
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.getBackground().setAlpha(50);//设置透明度
        popupWindow.setOutsideTouchable(true);//设置可以点击
        popupWindow.setFocusable(true);//使popupwindow获得焦点
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        //获取控件
        iv_picture = (ImageView) view.findViewById(R.id.pop_bag_image);
        tv_sum = (TextView) view.findViewById(R.id.pop_bag_sum);
        tv_name = (TextView) view.findViewById(R.id.pop_bag_text);
        tv_price = (TextView) view.findViewById(R.id.pop_bag_price);
        btn_minus = (ImageButton) view.findViewById(R.id.pop_bag_minus);
        btn_plus = (ImageButton) view.findViewById(R.id.pop_bag_plus);
        btn_sure = (Button) view.findViewById(R.id.btn_pop_sure);

        tv_sum.setOnClickListener(this);
        btn_minus.setOnClickListener(this);
        btn_plus.setOnClickListener(this);
        btn_sure.setOnClickListener(this);
    }

    private void showPopupWindow(int position) {
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(
                getActivity()).threadPoolSize(5).build();
        ImageLoader.getInstance().init(configuration);
        //ImageLoader配置
        DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.mipmap.error)
                .displayer(new FadeInBitmapDisplayer(100)).displayer(new RoundedBitmapDisplayer(50)).build();
        //头像
        ImageLoader.getInstance().displayImage(clothInfoList.get(position).getWashHead(), iv_picture, options);
        tv_price.setText(clothInfoList.get(position).getAmount());
        tv_name.setText(clothInfoList.get(position).getWashName());
    }

    @Override
    public void onClick(View v) {

    }
}
